<?php

declare(strict_types=1);

namespace AuthKit\JsonRpcSignature;

use AuthKit\JsonRpcSignature\Engine\SignatureEngineInterface;
use Contract\Exceptions\ValidationException;

class JsonRpcSignatureService
{
    /**
     * @var SignatureEngineInterface
     */
    private SignatureEngineInterface $signatureEngine;

    public function __construct(SignatureEngineInterface $signatureEngine)
    {
        $this->signatureEngine = $signatureEngine;
    }

    /**
     * @param string $appId
     * @param int $timestamp
     * @param string $nonce
     * @param string $body
     * @param string $appSecret
     * @return string
     * @throws ValidationException
     */
    public function generate(string $appId, int $timestamp, string $nonce, string $body, string $appSecret): string
    {
        if (empty($appId)) {
            throw new ValidationException('appId 不能为空');
        }
        if (empty($timestamp)) {
            throw new ValidationException('timestamp 不能为空');
        }
        if (empty($nonce)) {
            throw new ValidationException('nonce 不能为空');
        }
        if (empty($body)) {
            throw new ValidationException('body 不能为空');
        }
        if (empty($appSecret)) {
            throw new ValidationException('appSecret 不能为空');
        }
        $params = [$appId, $timestamp, $nonce, $body, $appSecret];
        return $this->signatureEngine->generate($params);
    }

    /**
     * @param string $appId
     * @param int $timestamp
     * @param string $nonce
     * @param string $body
     * @param string $appSecret
     * @param string $signature
     * @return bool
     */
    public function verify(string $appId, int $timestamp, string $nonce, string $body, string $appSecret, string $signature): bool
    {
        $params = [$appId, $timestamp, $nonce, $body, $appSecret];
        $expectSignature = $this->signatureEngine->generate($params);
        return $expectSignature === $signature;
    }

    /**
     * @return array
     */
    public function getDebugInfo(): array
    {
        return $this->signatureEngine->getDebugInfo();
    }

}